#include <stdio.h>
#include <stdlib.h>

/*
	编写函数，实现反转链表功能。
*/

typedef struct node{
	int data;
	struct node * next;
}Chain;

Chain * create(int n){
	int i;
	Chain * head=(Chain*)malloc(sizeof(Chain));
	Chain * tail=head;
	for(i=1;i<n;i++){
		tail->next=(Chain*)malloc(sizeof(Chain));
		tail=tail->next;
	}
	tail->next=NULL;
	return head;
};

void destroy(Chain * head){
	Chain * step,* out;
	for(step=head;step->next!=NULL;){
		out=step;
		step=step->next;
		free(out);
	}
}

Chain * reverse(Chain * head){
	int count=1;
	Chain * p=head;
	while(p->next!=NULL){
		count++;
		p=p->next;
	}
	Chain * nodes[count];
	int i;
	for(i=0,p=head;i<count;i++){
		nodes[i]=p;
		p=p->next;
	}
	i--;
	nodes[0]->next=NULL;
	while(i>0){
		nodes[i]->next=nodes[i-1];
		i--;
	}
	return nodes[--count];
}

int main(){
	int n;
	printf("Enter an integer: ");
	scanf("%d",&n);
	struct node * chain=create(n);
	struct node * p=chain;
	while(p->next!=NULL){
		printf("%p ",p);
		p=p->next;
	}
	printf("%p\n",p);
	chain=reverse(chain);
	for(p=chain;p->next!=NULL;p=p->next){
		printf("%p ",p);
	}
	printf("%p\n",p);
	destroy(chain);
	return 0;
}

